package org.leon.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.leon.bean.UserFile;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * Created by Administrator on 2017/4/26.
 */
@Controller
@RequestMapping(value = "/fileupload")
public class FileUploadController {
    private static  final Log logger = LogFactory.getLog(FileUploadController.class);

    /**
     * upload page
     * @return
     */
    @RequestMapping(value = "/uploadForm")
    public String uploadForm(){
        return "fileupload/uploadForm";

    }

    /**
     * file upload onto server
     * @param request
     * @param description
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload")
    public String upload(HttpServletRequest request,
                         @RequestParam("description") String description,
                         @RequestParam("file")MultipartFile file) throws Exception{
        logger.info(description);
        if(!file.isEmpty()){
            String path = request.getServletContext().getRealPath("/images");
            String filename = file.getOriginalFilename();
            File filepath = new File(path,filename);
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            file.transferTo(new File(path+File.separator+filename));
            logger.info(path+File.separator+filename);
            return "fileupload/success";
        }else{
            return "fileupload/error";
        }
    }

    /**
     * user upload file web page
     * @return
     */
    @RequestMapping(value = "/registerForm")
    public String registerForm(){
        return "fileupload/registerForm";

    }

    /**
     * user register
     *          -> upload
     * @param request
     * @param user
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/register")
    public String register(HttpServletRequest request,
                        @ModelAttribute UserFile user,
                         Model model) throws Exception{
        logger.info(user.getUsername());
        if(!user.getFile().isEmpty()){
            String path = request.getServletContext().getRealPath("/images");
            String filename = user.getFile().getOriginalFilename();
            File filepath = new File(path,filename);
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            user.getFile().transferTo(new File(path+File.separator+filename));
            logger.info(path+File.separator+filename);

            model.addAttribute("user",user);

            // to download page
            return "fileupload/userInfo";
        }else{
            return "fileupload/error";
        }
    }

    /**
     * down load file
     * @param request
     * @param filename
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model) throws Exception {
        // down load path
        String path = request.getServletContext().getRealPath("/images/");
        
        File file = new File(path+File.separator+filename);

        HttpHeaders headers = new HttpHeaders();

        // show Chinese File Name, solve charset problems
        String downLoadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");

        // inform Browser to open file by attachment
        headers.setContentDispositionFormData("attachment", downLoadFileName);

        // binary data stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 201 HttpStatus.Created
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);

    }
}
